import {
  CREATE,
  DELETE,
  EDITOR,
  STATE_CHANGE
} from '../constants/actionTypes';

//根据store的传来的原数据和action,数据处理
const todoList = (state = [], action) => {
  switch (action.type) {

    // 添加一条到list
    case CREATE:
      return [
        ...state,
        {
          id: state.length == 0 ? 0 : state[state.length-1].id + 1,
          text: action.text,
          checked: false
        }
      ];

    //删除list中指定项
    case DELETE:
      var deleteIndex = arrayIdToIndex(state, action.id);

      return [
        ...state.slice(0, deleteIndex),
        ...state.slice(parseInt(deleteIndex) + 1)
      ];

    //编辑list中指定项
    case EDITOR:
      var editorIndex = arrayIdToIndex(state, action.id);

      return [
        ...state.slice(0, editorIndex),
        Object.assign({}, state[editorIndex], {
          text: action.text
        }),
        ...state.slice(parseInt(editorIndex) + 1)
      ];

    //改变list中指定项状态
    case STATE_CHANGE:
      var stateChangeIndex = arrayIdToIndex(state, action.id);

      return [
        ...state.slice(0, stateChangeIndex),
        Object.assign({}, state[stateChangeIndex], {
          checked: !state[stateChangeIndex].checked
        }),
        ...state.slice(parseInt(stateChangeIndex) + 1)
      ];

    default:
      return state;
  }
}

// 根据id获取在数组中的位置
const arrayIdToIndex = (array, id) => {
  var index;
  for (let i in array) {

    if (array[i].id == id) {

      index = i;
      break;
    }
  }
  return index;
}

export default todoList;